package com.mentaleye.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.mentaleye.bean.PermissionsRoleKeyBean;
import com.mentaleye.biz.PermissionsRoleBiz;
import com.mentaleye.util.CommonResult;

@Controller
@RequestMapping("/rolePermission")
public class RolePermissionController {

	@Autowired private PermissionsRoleBiz permissionsRoleBiz;
	
	@RequestMapping(value = "/save")
	@ResponseBody
	public String save(@RequestParam(value = "roleNo", required = false) Integer roleNo,@RequestParam(value = "param", required = false)  int[] ids){
		List<PermissionsRoleKeyBean> list = permissionsRoleBiz.queryPermissionsRole(roleNo);
		if(list.size()>0){
			permissionsRoleBiz.deletePermissionsRole(roleNo);
			if(ids !=null && ids.length>1){
				List<PermissionsRoleKeyBean> beanlist = new ArrayList<PermissionsRoleKeyBean>();
				for(int i=0;i<ids.length;i++){
					PermissionsRoleKeyBean permissionRole = new PermissionsRoleKeyBean();
					permissionRole.setRoleNo(roleNo);
					permissionRole.setPermissionsId(ids[i]);
					beanlist.add(permissionRole);
				}
				return JSONObject.toJSONString(new CommonResult(permissionsRoleBiz.addPermissiosRoleBeanList(beanlist)));
			}else{
				PermissionsRoleKeyBean permissionBean = new PermissionsRoleKeyBean();
				permissionBean.setPermissionsId(ids[0]);
				permissionBean.setRoleNo(roleNo);
				return JSONObject.toJSONString(new CommonResult(permissionsRoleBiz.addPermissiosRoleBean(permissionBean)));
			}
		}else{
			if(ids !=null && ids.length>1){
				List<PermissionsRoleKeyBean> beanlist = new ArrayList<PermissionsRoleKeyBean>();
				for(int i=0;i<ids.length;i++){
					PermissionsRoleKeyBean permissionRole = new PermissionsRoleKeyBean();
					permissionRole.setRoleNo(roleNo);
					permissionRole.setPermissionsId(ids[i]);
					beanlist.add(permissionRole);
				}
				return JSONObject.toJSONString(new CommonResult(permissionsRoleBiz.addPermissiosRoleBeanList(beanlist)));
			}else{
				PermissionsRoleKeyBean permissionBean = new PermissionsRoleKeyBean();
				permissionBean.setPermissionsId(ids[0]);
				permissionBean.setRoleNo(roleNo);
				return JSONObject.toJSONString(new CommonResult(permissionsRoleBiz.addPermissiosRoleBean(permissionBean)));
			}
		}
	}
	
	@RequestMapping("/getPermissionByNo")
	@ResponseBody
	public String getPermissionsByRoleNo(@RequestParam(value="roleNo",required = false) Integer roleNo){
		
		return JSONObject.toJSONString(permissionsRoleBiz.queryPermissionsRole(roleNo));
	}
}
